#include "CustomExport.h"

// this fuction decides what type of output will be made from the xml and will also name it
void CustomExport::write(string outputName, string outputType, sc_object* top)
{
	mOutputType = outputType;
	mOutputName = outputName;

	XMLExport::write(INTERMEDIATE_OUTPUT_NAME, top);
}

//This function generates an output 
void CustomExport::generateOutput(string outputName)
{	////gets the SystemC2XML/Settings path
	string filePath = string(getenv(ROOT_DIR)).append("Settings\\");
	//Creaets and loads a file
	TiXmlDocument settings( filePath.append("ExportSettings.xml").c_str() );
	settings.LoadFile();
	TiXmlElement* outputType = settings.FirstChildElement("ExportSettings")->FirstChildElement("OutputTypeList")->FirstChildElement();
	string name, xsl, fileExtension;

	//find the outputType in the ExportSettings.xml
	while (outputType)
	{
		name = outputType->Attribute("name");
		xsl = outputType->Attribute("xsl");
		fileExtension = outputType->Attribute("fileExtension");
		if (name == mOutputType) break;
		outputType = outputType->NextSiblingElement();
	}

	if (name == mOutputType)
	{   //generate an intermediate xml output
		XMLExport::generateOutput(outputName);

		TiXmlElement* processor = settings.FirstChildElement("ExportSettings")->FirstChildElement("XSLT_Processor");

		// generates and executes a command to run an XSL processor to generate the specified output
		string command = processor->GetText();
		command.replace(command.find("[input]"), 7, string(INTERMEDIATE_OUTPUT_NAME).append(".xml"));
		command.replace(command.find("[xsl]"), 5, xsl);
		command.replace(command.find("[output]"), 8, string(mOutputName).append(".").append(fileExtension));
		system(command.c_str());


	}
	else
	{
		cout << "Error: output format '" << mOutputName << "' unknown";
	}
}

